﻿using System;
using System.Text;
using PostSharp.Aspects;
using System.Diagnostics;

//[assembly: CalculateTime(AspectPriority = 1)]

namespace Framework.Common.AOP.Performance
{
    /// <summary>
    /// 计算方法时间
    /// </summary>
    [Serializable]
    public sealed class TimeAttribute : OnMethodBoundaryAspect
    {
        #region 构造函数
        public TimeAttribute()
            : this(0)
        {
        }

        public TimeAttribute(double tick)
        {
            _timeTick = tick;
            _timeBuilder = new StringBuilder();
        }
        #endregion

        #region 分隔符
        string _seperator = "\n\r";
        /// <summary>
        /// 分割符(调整格式,利于分析日志)
        /// </summary>
        public String Seperator
        {
            get
            {
                return _seperator;
            }
            set
            {
                _seperator = value;
            }
        }
        #endregion

        #region 私有字段
        private readonly StringBuilder _timeBuilder;
        private readonly double _timeTick;
        [NonSerialized]
        private Stopwatch _stopWatch;
        #endregion

        #region 是否记录URL
        bool _recordUrl;
        public bool RecordUrl
        {
            get { return _recordUrl; }
            set { _recordUrl = value; }
        }
        #endregion

        public override void OnEntry(MethodExecutionArgs eventArgs)
        {
            _timeBuilder.Clear();
            _timeBuilder.Append("MethodName:");
            _timeBuilder.Append(Formatter.Format(eventArgs));
            _stopWatch = Stopwatch.StartNew();
        }

        public override void OnExit(MethodExecutionArgs eventArgs)
        {
            _stopWatch.Stop();
            long elapsedMilliseconds = _stopWatch.ElapsedMilliseconds;
            if (_timeTick <= 0 || elapsedMilliseconds > _timeTick)
            {
                _timeBuilder.Append(Seperator);
                _timeBuilder.Append("ElapsedMilliseconds:");
                _timeBuilder.Append(elapsedMilliseconds);
                _timeBuilder.Append(Seperator);
                _timeBuilder.Append("CompleteTime:");
                _timeBuilder.Append(DateTime.Now);
                if (RecordUrl)
                {
                    string url = System.Web.RequestExtention.GetUrl();
                    if (!url.IsBlank())
                    {
                        _timeBuilder.Append(Seperator);
                        _timeBuilder.Append("URL:");
                        _timeBuilder.Append(url);
                    }
                }
                LogHelper.Debug(_timeBuilder);
            }
        }
    }
}
